package com.ymttest.common.order.sellerquery2;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Lists;
import com.shop2cn.iapi.sqsynctrade.paremeter.mongo.details.Fund;
import com.shop2cn.iapi.sqsynctrade.paremeter.mongo.details.Refund;
import com.ymatou.common.lang.CipherUtil;
import com.ymatou.iapi.synctrade.parameter.mongo.Order;
import com.ymatou.iapi.trading.ordersync.service.BigDecimalUtil;
import com.ymatou.query.seller.trading.api.parameter.info.OrderBasicInfo;
import com.ymatou.query.seller.trading.api.parameter.info.OrderConsigneeInfo;
import com.ymatou.query.seller.trading.api.parameter.info.OrderConsumerInfo;
import com.ymatou.query.seller.trading.api.parameter.info.OrderPaymentDetail;
import com.ymatou.query.seller.trading.api.parameter.info.OrderPaymentInfo;
import com.ymatou.query.seller.trading.api.parameter.info.OrderProductInfo;
import com.ymatou.query.seller.trading.api.parameter.info.OrderProductRefundInfo;
import com.ymatou.query.seller.trading.api.parameter.info.OrderSellerInfo;
import com.ymatou.query.seller.trading.api.parameter.info.OrderTransferInfo;
import com.ymatou.query.seller.trading.api.parameter.info.SellerOrderInfo;
import com.ymttest.common.order.sellerquery2.model.FundSummary;
import com.ymttest.common.order.userquery.util.OrderHelper;
import com.ymttest.common.order.userquery.util.Utils;

public class SellerOrderInfoBuilder {

	public static FundSummary buildFundSummary(Order order) {

		Fund f = order.getFund();
		FundSummary fundSummary = new FundSummary();

		fundSummary.setTotalProductPrice(order.getTotalPrice());
		fundSummary.setFirstPayProductPrice(order.getOrderPrice());
		fundSummary.setFreight(order.getFreight());
		fundSummary.setOrderDiscount(order.getPreDiscount());
		fundSummary.setPostPayDiscount(order.getPostDiscount());
		fundSummary.setTotalActivityPrice(Utils.zeroIfNull(order
				.getSellerPromotionAmount()));

		fundSummary.setPaidCash(f.getPaidCash());
		fundSummary.setPaidGift(f.getPaidGif());
		fundSummary.setPaidFreeCard(f.getPaidFreeCard());
		fundSummary.setPaidYmtCoupon(f.getYmtCoupon());
		fundSummary.setPaidSellerCoupon(f.getSellerCoupon());
		fundSummary.setPostPaidCash(f.getPostCash());
		fundSummary.setPostPaidGift(f.getPostGif());
		fundSummary.setTotalThirdPartyDiscount(f.getDiscount3P());
		fundSummary.setPaidAccount(f.getPaidAccount());
		fundSummary.setPaidThirdParty(f.getPaid3P());
		fundSummary.setPrePaidCard(f.getPrepaidCard());

		// 退款相关
		fundSummary.setTotalRefundedCash(f.getRefundCash());
		fundSummary.setTotalRefundedGift(f.getRefundGif());
		fundSummary.setTotalRefundedYmtCoupon(f.getRefundCoupon());
		fundSummary.setTotalRefundedThirdPartyDiscount(f.getRefundDiscount3P());

		return fundSummary;
	}

	/**
	 * 原sqlserver 依赖 sp_trd_GetOrdersByOrderIds_v2
	 *
	 * @param orderList
	 * @return
	 * @throws Exception 
	 */
	public static List<SellerOrderInfo> convertBySellerOrder(
			List<Order> orderList, long sellerId) throws Exception {
		List<SellerOrderInfo> list = Lists.newArrayList();
		if (!CollectionUtils.isEmpty(orderList)) {
			for (Order order : orderList) {
				// 增加兼容-1
				if (sellerId != -1
						&& order.getSellerId() != sellerId
						&& Utils.zeroIfNull(order.getGoodsOwnerId()) != sellerId) {
					continue; // 非当前买手订单不返回
				}

				SellerOrderInfo sellerOrderInfo = new SellerOrderInfo();

				// 订单基本信息
				OrderBasicInfo basic = new OrderBasicInfo();
				basic.setId(order.getId());
				basic.setMainOrderId(order.getMainOrderId());
				basic.setType(BigDecimalUtil.isEqual(order.getOrderPrice(),
						order.getTotalPrice()) ? 0 : 1); // xxx
															// 确认原存储过程使用bShangouOrder
															// 现都使用默认值0
				basic.setStatus(order.getTradingStatus());
				basic.setSource(order.getPlatSource());
				basic.setTotalPrice(order.getTotalPrice());
				basic.setDiscount(order.getPreDiscount());
				basic.setCreatedTime(order.getAddTime());
				basic.setCancelledTime(order.getCancelTime());
				basic.setAcceptedTime(order.getAcceptTime());
				basic.setPreSaleOrder(order.isPreSale());
				basic.setBizType(order.getBizType());

				// 订单买家信息
				OrderConsumerInfo buyer = new OrderConsumerInfo();
				buyer.setId(order.getUserId() + "");
				buyer.setLoginId(order.getUserLogin());
				buyer.setNickName(order.getUserLogin()); // nickname
															// 使用userlogin一样的
				buyer.setEmail(order.getEmail());
				buyer.setMessage(order.getComment());

				// 订单卖家信息
				OrderSellerInfo seller = new OrderSellerInfo();
				seller.setId(order.getSellerId() + "");
				seller.setLoginId(order.getSellerLogin());
				seller.setComment(StringUtils.defaultString(order.getContent()));

				// 收货人信息
				OrderConsigneeInfo consignee = new OrderConsigneeInfo();
				consignee.setName(order.getReceiver());
				consignee.setAddress(Utils.hiddenAddress(CipherUtil.decryptAES(
						"123456789", order.getUaddress())));
				consignee.setPhone(Utils.hiddenPhone(CipherUtil.decryptAES(
						"123456789", order.getUphone())));
				consignee.setTel(order.getTelephone());
				consignee.setPostcode(order.getPostCode());

				// 订单支付信息
				OrderPaymentInfo payment = new OrderPaymentInfo();
				payment.setTradingId(order.getTradingId());
				// xxx 原存储过程减了运费、暂时这边不处理
				payment.setActualPaid(Utils.zeroIfNull(
						order.getFund().getPaidCash()).add(
						Utils.zeroIfNull(order.getFund().getPostCash())));
				payment.setSummary(buildFundSummary(order));

				List<OrderPaymentDetail> paymentDetailList = Lists
						.newArrayList();
				
				if (order.getPaidTime() != null) {
					OrderPaymentDetail paymentDetail = new OrderPaymentDetail();
					paymentDetail.setType(1);
					paymentDetail.setPaidTime(order.getPaidTime());
					paymentDetail.setInternalTradingNo(order.getTradingId()
							+ "");
					paymentDetail.setExternalTradingNo(order.getTradeNo());// 第三方支付单号
																			// tradinginfo表sTradeNo
					paymentDetailList.add(paymentDetail);
				}
				
				if (order.getPostTime() != null) {
					OrderPaymentDetail paymentDetail = new OrderPaymentDetail();
					paymentDetail.setType(2);
					paymentDetail.setPaidTime(order.getPostTime());
					paymentDetailList.add(paymentDetail);
				}
				
				payment.setDetails(paymentDetailList);

				OrderTransferInfo transfer = new OrderTransferInfo();
				transfer.setDeliveredTime(order.getDeliveryTime());
				transfer.setReceiptConfirmedTime(order.getReceiveTime());
				transfer.setDomesticDelivery(order.isLocalDelivery());

				// 订单商品信息
				List<OrderProductInfo> products = Lists.newArrayList();
				if (!CollectionUtils.isEmpty(order.getProducts())) {

					List<Refund> refundList = order.getRefunds();

					order.getProducts()
							.forEach(
									product -> {
										OrderProductInfo productInfo = new OrderProductInfo();
										productInfo.setName(product.getTitle());
										productInfo.setCatalogId(product
												.getCataId());
										productInfo.setCatalogType(product
												.getStockStatus());
										productInfo.setPackageNo(product
												.getPackageNo());
										productInfo.setProductId(product
												.getProductId());
										productInfo.setBondedArea(Utils
												.zeroIfNull(product
														.getBondedArea()));
										productInfo.setCount(product
												.getPrdCount());
										productInfo.setLogistics(OrderHelper
												.isShenqiOrder(order) ? order
												.getShenqiLogisticsType()
												: product.getDeliveryType());
										productInfo.setActivityId(Utils
												.zeroIfNull(product.getActId()));
										productInfo.setPrice(product
												.getPrdPrice());
										productInfo.setPropertyInfo(product
												.getPropertyInfo());
										productInfo.setSku(product.getSku());
										productInfo.setTotalPrice(Utils
												.zeroIfNull(
														product.getPrdPrice())
												.multiply(
														new BigDecimal(product
																.getPrdCount())));
										productInfo.setCategories(Lists
												.newArrayList(
														product.getCata1Id(),
														product.getCata2Id(),
														product.getCata3Id()));
										productInfo.setOriginalPrice(product
												.getPrdOriginalPrice());
										productInfo.setPartialFreight(product
												.getPrdFreight());
										productInfo.setPartialYmtCoupon(product
												.getPrdYmtCoupon());
										productInfo.setPartialDiscount(product
												.getPrdDiscount());
										productInfo
												.setPartialSellerCoupon(product
														.getPrdSellerCoupon());
										productInfo
												.setPartialSellerPromotion(product
														.getPrdPromotionAmount());
										productInfo.setPartialYmtPromotion(Utils.zeroIfNull(product
												.getPrdYmtPromotionAmount()));
										productInfo.setBrandId(Utils
												.zeroIfNull(product
														.getBrandId()));
										productInfo.setThirdPartyDiscount(Utils
												.zeroIfNull(product
														.getPrdDiscount3P()));
										productInfo.setPreSale(order
												.isPreSale());
										productInfo.setPspProduct(product
												.isPspProduct());
										productInfo.setSubProductInfos(OrderHelper
												.buildSubProducts(order,
														product.getCataId()));
										productInfo.setFreightFree(product
												.isFreightFree());
										productInfo.setEarnestAmount(Utils
												.zeroIfNull(product
														.getEarnestAmount()));
										productInfo
												.setBookingPromotionAmount(Utils.zeroIfNull(product
														.getBookingPromotionAmount()));

										if (product.getPrdRefundStatus() != null) {

											// 如果商品有退款 找到对应退款信息
											Refund r = refundList
													.stream()
													.filter(refund -> refund
															.getRefundNo()
															.equals(product
																	.getPrdRefundNo())
															&& product
																	.getPrdRefundStatus()
																	.equals(10))
													.findFirst().orElse(null);

											if (null != r) {
												OrderProductRefundInfo refundInfo = new OrderProductRefundInfo();
												refundInfo.setRefundAmount(r
														.getRefundAmount());
												refundInfo
														.setRefundedAmountOfCash(r
																.getRefundAmountCash());
												refundInfo
														.setRefundedAmountOfGift(r
																.getRefundAmountGift());
												refundInfo
														.setRefundProductNum(new BigDecimal(
																product.getRefundCount()));
												refundInfo.setRefundStatus(1); // xxx
																				// 退款完成
																				// 无用
												refundInfo.setSalesRefundStatus(r
														.getRefundStatus());
												refundInfo
														.setSettlementAmountOfCoupon(r
																.getRefundAmountCop());
												refundInfo
														.setRefundedAmountOfYmtPromotion(Utils.zeroIfNull(r
																.getRefundAmountProm()));
												refundInfo
														.setRefundedDiscountOfThirdParty(r
																.getRefund3P());
												productInfo
														.setRefundInfo(refundInfo);
											}
										}

										products.add(productInfo);
									});
				}

				sellerOrderInfo.setBasic(basic);
				sellerOrderInfo.setBuyer(buyer);
				sellerOrderInfo.setSeller(seller);
				sellerOrderInfo.setConsignee(consignee);
				sellerOrderInfo.setPayment(payment);
				sellerOrderInfo.setTransfer(transfer);
				sellerOrderInfo.setProducts(products);

				list.add(sellerOrderInfo);
			}
		}
		
		return list;
	}
}
